package cn.hbads.version.parser.model;

import cn.hbads.version.annotation.FieldVersion;
import cn.hbads.version.provider.DynNameProvider;
import cn.hbads.version.provider.MessageProvider;
import cn.hbads.version.provider.ValueTranslator;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;

/**
 * <b>描述 @FieldVersion的信息的解析模型</b>
 *
 * @author : yvvb
 * @date : 2025/5/5
 */
@Data
@Builder
@AllArgsConstructor
public class FieldVersionModel implements VersionModel {

    private String fieldName;
    private Class<?> fieldClass;
    private String name;
    private DynNameProvider dynNameProvider;
    private ValueTranslator valueTranslator;
    private MessageProvider messageProvider;
    private int showOrder;

    public static FieldVersionModel buildFrom(Field field, FieldVersion fieldVersion) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Optional<DynNameProvider> dynNameProviderOpt = Optional.empty();
        if (!fieldVersion.dynNameClass().equals(DynNameProvider.class)) {
            dynNameProviderOpt = Optional.of(fieldVersion.dynNameClass().getDeclaredConstructor().newInstance());
        }
        Optional<ValueTranslator> translatorOpt = Optional.empty();
        if (!fieldVersion.translatorClass().equals(ValueTranslator.class)) {
            translatorOpt = Optional.of(fieldVersion.translatorClass().getDeclaredConstructor().newInstance());
        }
        Optional<MessageProvider> msgProviderOpt = Optional.empty();
        if (!fieldVersion.msgProviderClass().equals(MessageProvider.class)) {
            msgProviderOpt = Optional.of(fieldVersion.msgProviderClass().getDeclaredConstructor().newInstance());
        }
        return FieldVersionModel.builder()
                .fieldName(field.getName())
                .fieldClass(field.getType())
                .name(fieldVersion.name())
                .dynNameProvider(dynNameProviderOpt.orElse(null))
                .valueTranslator(translatorOpt.orElse(null))
                .messageProvider(msgProviderOpt.orElse(null))
                .showOrder(fieldVersion.showOrder())
                .build();
    }
}
